// 传入一个拖动的dragEl和一个目标targetEl，拖动dragEl去更新targetEl位置
export function useDraggable(
  targetEl,
  dragEl,
  options = { overflow: false }
) {
  let transform = {
    offsetX: 0,
    offsetY: 0
  };
  const {overflow} = options;

  const onMousedown = (e) => {
    const downX = e.clientX;
    const downY = e.clientY;
    const { offsetX, offsetY } = transform;

    const targetRect = targetEl.getBoundingClientRect();
    const targetLeft = targetRect.left;
    const targetTop = targetRect.top;
    const targetWidth = targetRect.width;
    const targetHeight = targetRect.height;

    const clientWidth = document.documentElement.clientWidth;
    const clientHeight = document.documentElement.clientHeight;

    const minLeft = -targetLeft + offsetX;
    const minTop = -targetTop + offsetY;
    const maxLeft = clientWidth - targetLeft - targetWidth + offsetX;
    const maxTop = clientHeight - targetTop - targetHeight + offsetY;

    const onMousemove = (e) => {
      let moveX = offsetX + e.clientX - downX;
      let moveY = offsetY + e.clientY - downY;

      if (!overflow) {
        moveX = Math.min(Math.max(moveX, minLeft), maxLeft);
        moveY = Math.min(Math.max(moveY, minTop), maxTop);
      }

      transform = {
        offsetX: moveX,
        offsetY: moveY
      };

      if (targetEl) {
        targetEl.style.transform = `translate(${moveX}px, ${moveY}px)`;
      }
    };

    const onMouseup = () => {
      console.log('drag on mouse up');
      document.removeEventListener('mousemove', onMousemove);
      document.removeEventListener('mouseup', onMouseup);
    };

    document.addEventListener('mousemove', onMousemove);
    document.addEventListener('mouseup', onMouseup);
  };

  const onDraggable = () => {
    if (dragEl && targetEl) {
      dragEl.addEventListener('mousedown', onMousedown);
    }
  };

  const offDraggable = () => {
    if (dragEl && targetEl) {
      dragEl.removeEventListener('mousedown', onMousedown);
    }
  };

  const resetPosition = () => {
    transform = {
      offsetX: 0,
      offsetY: 0
    };
    if (targetEl) {
      targetEl.style.transform = 'none';
    }
  };

  return {
    onDraggable,
    offDraggable,
    resetPosition
  };
}
